﻿using MediatR;
using MS.Data.API.Read.Command.User;
using MS.Data.Domain;
using MS.Data.ErrorCode;
using MS.Data.Infratructrue.Istanbul;

namespace MS.Data.API.Read.CommandHandle.User
{

    public class GetUserCommandHandel : IRequestHandler<GetUserCommand, APIResult<APIPing<Domain. User>>>
    {
        IBaseRepository<Domain. User> userRep;
        IBaseRepository<RoleUser> ruRep;
        IBaseRepository<Role> roleRep;

        public GetUserCommandHandel(IBaseRepository<Domain.User> userRep, IBaseRepository<RoleUser> ruRep, IBaseRepository<Role> roleRep)
        {
            this.userRep = userRep;
            this.ruRep = ruRep;
            this.roleRep = roleRep;
        }

        public Task<APIResult<APIPing<Domain.User>>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPing<Domain.User>> result= new APIResult<APIPing<Domain.User>>();
            result.code = APIEnum.显示成功;
            result.mes = APIEnum.显示成功.ToString();

            var list = from a in userRep.GetAll()

                       where !a.IsDel
                       select new Domain.User()
                       {
                           UserId=a.UserId,
                           UserName=a.UserName,
                           UserPwd=a.UserPwd,
                           NickName=a.NickName,
                           State=a.State,
                           CreaTime=a.CreaTime,
                           RoleName=a.RoleName,
                       };
            if (!string.IsNullOrEmpty(request.RoleName))
            {
                list = list.Where(s => s.RoleName.Contains(request.RoleName));
            }

            int totalCount=list.Count();
            int pageCount=(int)Math.Ceiling(totalCount*1.0/request.pageSize);

            list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

            APIPing<Domain.User> page = new APIPing<Domain.User>()
            {
                totalCount=totalCount,
                pageCount=pageCount,
                pageData=list.ToList(),
            };
            result.data = page;

            return Task.FromResult(result);
        }
    }
}
